package com.test.Servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.output.eps.EPSCanvasProvider;
import org.krysalis.barcode4j.output.svg.SVGCanvasProvider;
import org.krysalis.barcode4j.tools.MimeTypes;
import org.w3c.dom.DocumentFragment;

public class BarcodeServlet extends HttpServlet {
	private static final long serialVersionUID = -1612710758060435089L;
	public static final String BARCODE_MSG = "msg";
	public static final String BARCODE_TYPE = "type";
	public static final String BARCODE_HEIGHT = "height";
	public static final String BARCODE_MODULE_WIDTH = "mw";
	public static final String BARCODE_WIDE_FACTOR = "wf";
	public static final String BARCODE_QUIET_ZONE = "qz";
	public static final String BARCODE_HUMAN_READABLE_POS = "hrp";
	public static final String BARCODE_FORMAT = "fmt";
	public static final String BARCODE_IMAGE_RESOLUTION = "res";
	public static final String BARCODE_IMAGE_GRAYSCALE = "gray";
	public static final String BARCODE_HUMAN_READABLE_SIZE = "hrsize";
	public static final String BARCODE_HUMAN_READABLE_FONT = "hrfont";
	public static final String BARCODE_HUMAN_READABLE_PATTERN = "hrpattern";
	private transient Logger log = new ConsoleLogger(1);

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String format = determineFormat(request);
			int orientation = 0;

			Configuration cfg = buildCfg(request);

			String msg = request.getParameter("msg");
			if (msg == null) {
				msg = "0123456789";
			}

			BarcodeUtil util = BarcodeUtil.getInstance();
			BarcodeGenerator gen = util.createBarcodeGenerator(cfg);

			ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
			try {
				if (format.equals("image/svg+xml")) {
					SVGCanvasProvider svg = new SVGCanvasProvider(false,
							orientation);
					gen.generateBarcode(svg, msg);
					DocumentFragment frag = svg.getDOMFragment();

					TransformerFactory factory = TransformerFactory
							.newInstance();
					Transformer trans = factory.newTransformer();
					Source src = new DOMSource(frag);
					Result res = new StreamResult(bout);
					trans.transform(src, res);
				} else if (format.equals("image/x-eps")) {
					EPSCanvasProvider eps = new EPSCanvasProvider(bout,
							orientation);
					gen.generateBarcode(eps, msg);
					eps.finish();
				} else {
					String resText = request.getParameter("res");
					int resolution = 300;
					if (resText != null) {
						resolution = Integer.parseInt(resText);
					}
					if (resolution > 2400) {
						throw new IllegalArgumentException(
								"Resolutions above 2400dpi are not allowed");
					}

					if (resolution < 10) {
						throw new IllegalArgumentException(
								"Minimum resolution must be 10dpi");
					}

					String gray = request.getParameter("gray");
					BitmapCanvasProvider bitmap = "true".equalsIgnoreCase(gray) ? new BitmapCanvasProvider(
							bout, format, resolution, 10, true, orientation)
							: new BitmapCanvasProvider(bout, format,
									resolution, 12, false, orientation);

					gen.generateBarcode(bitmap, msg);
					bitmap.finish();
				}
			} finally {
				bout.close();
			}
			response.setContentType(format);
			response.setContentLength(bout.size());
			response.getOutputStream().write(bout.toByteArray());
			response.getOutputStream().flush();
		} catch (Exception e) {
			this.log.error("Error while generating barcode", e);
			throw new ServletException(e);
		} catch (Throwable t) {
			this.log.error("Error while generating barcode", t);
			throw new ServletException(t);
		}
	}

	protected String determineFormat(HttpServletRequest request) {
		String format = request.getParameter("fmt");
		format = MimeTypes.expandFormat(format);
		if (format == null) {
			format = "image/svg+xml";
		}
		return format;
	}

	protected Configuration buildCfg(HttpServletRequest request) {
		DefaultConfiguration cfg = new DefaultConfiguration("barcode");

		String type = request.getParameter("type");
		if (type == null) {
			type = "code128";
		}
		DefaultConfiguration child = new DefaultConfiguration(type);
		cfg.addChild(child);

		String height = request.getParameter("height");
		if (height != null) {
			DefaultConfiguration attr = new DefaultConfiguration("height");
			attr.setValue(height);
			child.addChild(attr);
		}
		String moduleWidth = request.getParameter("mw");
		if (moduleWidth != null) {
			DefaultConfiguration attr = new DefaultConfiguration("module-width");
			attr.setValue(moduleWidth);
			child.addChild(attr);
		}
		String wideFactor = request.getParameter("wf");
		if (wideFactor != null) {
			DefaultConfiguration attr = new DefaultConfiguration("wide-factor");
			attr.setValue(wideFactor);
			child.addChild(attr);
		}
		String quietZone = request.getParameter("qz");
		if (quietZone != null) {
			DefaultConfiguration attr = new DefaultConfiguration("quiet-zone");
			if (quietZone.startsWith("disable"))
				attr.setAttribute("enabled", "false");
			else {
				attr.setValue(quietZone);
			}
			child.addChild(attr);
		}

		String humanReadablePosition = request.getParameter("hrp");
		String pattern = request.getParameter("hrpattern");
		String humanReadableSize = request.getParameter("hrsize");
		String humanReadableFont = request.getParameter("hrfont");

		if ((humanReadablePosition != null) || (pattern != null)
				|| (humanReadableSize != null) || (humanReadableFont != null)) {
			DefaultConfiguration attr = new DefaultConfiguration(
					"human-readable");

			if (pattern != null) {
				DefaultConfiguration subAttr = new DefaultConfiguration(
						"pattern");
				subAttr.setValue(pattern);
				attr.addChild(subAttr);
			}
			if (humanReadableSize != null) {
				DefaultConfiguration subAttr = new DefaultConfiguration(
						"font-size");
				subAttr.setValue(humanReadableSize);
				attr.addChild(subAttr);
			}
			if (humanReadableFont != null) {
				DefaultConfiguration subAttr = new DefaultConfiguration(
						"font-name");
				subAttr.setValue(humanReadableFont);
				attr.addChild(subAttr);
			}
			if (humanReadablePosition != null) {
				DefaultConfiguration subAttr = new DefaultConfiguration(
						"placement");
				subAttr.setValue(humanReadablePosition);
				attr.addChild(subAttr);
			}

			child.addChild(attr);
		}

		return cfg;
	}
}